# -*- coding: utf-8 -*-
"""
Created on Sat Nov  4 17:04:09 2017

@author: Luther
"""

import requests
import re
import json
import pandas as pd
from datetime import date
import time


def getMSFTStock():
    try:
        r = requests.get(
            'https://finance.yahoo.com/quote/MSFT/history?period1=1451577600&period2=1483113600&interval=1d&filter=history&frequency=1d'
        )
        r.raise_for_status
        r.encoding = r.apparent_encoding
        m = re.findall('"HistoricalPriceStore":{"prices":(.*?),"isPending"',
                       r.text)
        if m:
            quotes = json.loads(m[0])
            quotes = quotes[::-1]
        return [item for item in quotes if not 'type' in item]
    except:
        print('error!')


quotes = getMSFTStock()

list1 = []
for i in range(len(quotes)):
    x = date.fromtimestamp(quotes[i]['date'])
    y = date.strftime(x, '%Y-%m-%d')
    list1.append(y)
quotesdf_ori = pd.DataFrame(quotes, index=list1)

list2 = []
for i in range(len(quotes)):
    temp = time.strptime(quotesdf_ori.index[i], "%Y-%m-%d")
    list2.append(temp.tm_mon)
quotesdf_ori['month'] = list2

quotesdf = quotesdf_ori.drop(['date'], axis=1)
quotesdf = quotesdf[1:]
#print(quotesdf[:30])

mean = quotesdf.groupby('month').close.mean()
print(mean)
